import React from "react";
import {PropsWithChildren, useState} from "react";
import {MenuItem} from "@/types/menu";
import {TabContext} from "./context";
import {TabItem} from "@/types/tab";

export const TabProvider = ({ children }: PropsWithChildren) => {
  const [tabs, setTabs] = useState<TabItem[]>([
    {
      key: 'home',
      label: '首页',
      component: React.lazy(() => import('@/pages/home')),
      unclosable: 'true',
    },
  ]);
  const [activeTab, setActiveTab] = useState<MenuItem['key']>('home');

  const openTab = (menu: MenuItem) => {
    const existingTab = tabs.find(tab => tab.key === menu.key);
    if (!existingTab) {
      const newTab: TabItem = { key: menu.key, label: menu.label, component: React.lazy(menu.component), unclosable: menu.unclosable};
      setTabs(prev => [...prev, newTab]);
    }
    setActiveTab(menu.key);
  };

  const switchTab = (key: MenuItem['key']) => {
    setActiveTab(key);
  }

  return (
    <TabContext.Provider value={{ tabs, activeTab, openTab, switchTab }}>
      {children}
    </TabContext.Provider>
  );
};
